package com.cskaoyan.order.service.impl;

import com.cskaoyan.mall.commons.constant.SysRetCodeConstants;
import com.cskaoyan.mall.commons.exception.ExceptionProcessorUtils;
import com.cskaoyan.order.constant.OrderConstants;
import com.cskaoyan.order.dal.entitys.Order;
import com.cskaoyan.order.dal.entitys.OrderItem;
import com.cskaoyan.order.dal.entitys.Stock;
import com.cskaoyan.order.dal.persistence.OrderItemMapper;
import com.cskaoyan.order.dal.persistence.OrderMapper;
import com.cskaoyan.order.dal.persistence.StockMapper;
import com.cskaoyan.order.dto.CancelOrderRequest;
import com.cskaoyan.order.dto.CancelOrderResponse;
import com.cskaoyan.order.service.OrderUpdateService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;

/**
 * @author wjs
 * @ClassName OrderUpdateServiceImpl
 * @Description 创建日期: 2022/6/18 17:44
 */
@Slf4j
@Service
public class OrderUpdateServiceImpl implements OrderUpdateService {

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    OrderItemMapper orderItemMapper;

    @Autowired
    StockMapper stockMapper;
    @Override
    public CancelOrderResponse orderCancel(CancelOrderRequest request) {
        CancelOrderResponse response = new CancelOrderResponse();
        try {
            request.requestCheck();
            //更新order表
            Order order = new Order();
            order.setOrderId(request.getOrderId());
            order.setStatus(OrderConstants.ORDER_STATUS_TRANSACTION_CANCEL);
            order.setUpdateTime(new Date());
            orderMapper.updateByPrimaryKeySelective(order);

            //找出关联的item表，获取商品数量，返还库存
            List<OrderItem> orderItems = orderItemMapper.queryByOrderId(request.getOrderId());
            for (OrderItem orderItem : orderItems) {
                //返还每个商品的冻结库存
                Stock stock = new Stock();
                stock.setItemId(orderItem.getItemId());
                stock.setStockCount(Long.valueOf(orderItem.getNum()));
                stock.setLockCount(-orderItem.getNum());
                stockMapper.updateStock(stock);
            }
            response.setCode(SysRetCodeConstants.SUCCESS.getCode());
            response.setMsg(SysRetCodeConstants.SUCCESS.getMessage());
        }catch (Exception e){
            log.error("OrderUpdateServiceImpl.orderCancel occur Exception :"+e);
            ExceptionProcessorUtils.wrapperHandlerException(response,e);
        }
        return response;
    }
}
